/*
 * Title: WADS
 * Description: Web-based Auto flow Documents System
 * Copyright: 2007
 * Company: CoE
 * @author: Mr.Nattasan Wang-Aphisit
 * @version 1.1
 */

package wads.servlet;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Calendar;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import wads.com.AutoDocumentTransaction;
import wads.com.DocumentTemplateInfo;
import wads.com.UserInfo;
import wads.com.WADTools;

public class ManageFlowSystem extends HttpServlet{
  private static final long serialVersionUID = -6439887897671338459L;
  
  private static final String CONTENT_TYPE = WADTools.SERVLET_CONTENT_TYPE;
  /**Initialize global variables*/
  public final String hmtpServer = "mail.cablenet-va.com";
  public final int USER = 1;
  public final int EMAIL = 5;
  private AutoDocumentTransaction adTran;
  private DocumentTemplateInfo dtInfo;
  private String template_ID;
  private String transaction_ID;
  private String currentUser;
  private String app_Path;
  private String nextUser;
  private String email;
  private String comment;
  //private HttpSession session;
  private int accept;
  //private Vector history;
  //private String allComment = "";
  private File restrictUserFile;
  private UserInfo ui;
  private Calendar currentSubmitTime;


  public void init(ServletConfig config) throws ServletException {
    super.init(config);
  }
  /**Process the HTTP Get request*/
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType(CONTENT_TYPE);
    app_Path = WADTools.APP_PATH;
    restrictUserFile = new File(app_Path+"res/user/RestrictUser/RestrictUser.org");
    currentUser = request.getParameter("currentUser");
    currentSubmitTime = Calendar.getInstance();
    transaction_ID = request.getParameter("transaction_ID");
    accept = Integer.parseInt(request.getParameter("accept"));
    comment = request.getParameter("comment");

    String transaction_IDFile = "trans_" + transaction_ID + ".info";

    try{
      //Read Object of Document
      ObjectInputStream oisf = new ObjectInputStream(
          new  FileInputStream(app_Path+"res/docs/InProgressAutoDoc/" + currentUser + "/" + transaction_IDFile));
      adTran = (AutoDocumentTransaction)oisf.readObject();
      template_ID = adTran.getTemplate_ID();

      String currentTime = this.getTime();

      comment = currentUser + ":" + comment + ":" + currentTime;
      adTran.setSubmitDate(currentSubmitTime);
      adTran.addHistory(comment);
      adTran.setDocumentStatus(accept);

      ObjectInputStream oisa = new ObjectInputStream(
          new FileInputStream(app_Path+"res/docs/activeDocTemplate/" + template_ID + "/docTemplate.info"));
      dtInfo = (DocumentTemplateInfo)oisa.readObject();

      if(accept == 1){
        System.out.println("NextUser = " + dtInfo.whois_nextUser_from_thisUser(currentUser));
        if((nextUser = dtInfo.whois_nextUser_from_thisUser(currentUser)) != null){
          File dir = new File(app_Path+"res/docs/InProgressAutoDoc/" + nextUser);
          if(!dir.exists())
            dir.mkdir();
          ObjectOutputStream oosf = new ObjectOutputStream(
              new FileOutputStream(app_Path+"res/docs/InProgressAutoDoc/" + nextUser + "/" + transaction_IDFile));
          oosf.writeObject(adTran);
          oosf.close();
          response.sendRedirect("../success.html");
        }else{
          //Add code to Reply Email when end of flow
          System.out.println("No NextUser Of " + currentUser);
          ObjectOutputStream oosf = new ObjectOutputStream(
              new FileOutputStream(app_Path+"res/docs/SuccessDocument/" + transaction_IDFile));
          oosf.writeObject(adTran);
          oosf.close();
          //get email
          ObjectInputStream ois = new ObjectInputStream(new FileInputStream(restrictUserFile));
          ui = (UserInfo)ois.readObject();
          for(int i=0; i<ui.getSize(); i++){
            if((ui.getUserDataAt(i).getUsername()).equals(adTran.getOwner_Name()))
              email = ui.getUserDataAt(i).getEMail();
          }
          this.sendMail(email, "TESTAMENT");
          ois.close();
          response.sendRedirect("../success.html");
        }
      }else{
        System.out.println("BeforeUser = " + dtInfo.whois_lastUser_from_thisUser(currentUser));
        if((nextUser = dtInfo.whois_lastUser_from_thisUser(currentUser)) != null){
          ObjectOutputStream oosf = new ObjectOutputStream(
              new FileOutputStream(app_Path+"res/docs/InProgressAutoDoc/" + nextUser + "/" + transaction_IDFile));
          oosf.writeObject(adTran);
          oosf.close();
          response.sendRedirect("../success.html");
          //send mail
        }else{
          //Add code to Reply Email when back to user
          ObjectInputStream ois = new ObjectInputStream(new FileInputStream(restrictUserFile));
          ui = (UserInfo)ois.readObject();
          for(int i=0; i<ui.getSize(); i++){
            if((ui.getUserDataAt(i).getUsername()).equals(adTran.getOwner_Name()))
              email = ui.getUserDataAt(i).getEMail();
          }
          this.sendMail(email, "JUSTICE");
          response.sendRedirect("../success.html");
          ois.close();
        }
      }

      oisf.close();
      oisa.close();

      File f = new File(app_Path+"res/docs/InProgressAutoDoc/" + currentUser + "/" + transaction_IDFile);
      f.delete();
    }catch(Exception e){ e.printStackTrace(); }
  }

  /**Clean up resources*/
  public void destroy() {
  }

  public void sendMail(String email, String comment){
    PrintWriter out;
    BufferedReader in;
    System.out.println("Send Mail");
    try{
      Socket s = new Socket(hmtpServer,25);
      out = new PrintWriter(s.getOutputStream());
      in = new BufferedReader(new InputStreamReader(s.getInputStream()));
      out.println("HELLO a");
      out.flush();
      System.out.println(in.readLine());
      out.println("MAIL FROM:admin@coe.psu.ac.th");
      out.flush();
      System.out.println(in.readLine());
      out.println("RCPT TO:" + email);
      out.flush();
      System.out.println(in.readLine());
      out.println("DATA");
      out.write("Subject: Document flow report.\n");
      out.println(comment);
      out.println(".");
      out.flush();
      System.out.println(in.readLine());
      out.println("QUIT");
      out.flush();
      System.out.println(in.readLine());
      s.close();
      System.out.println("end");
    }catch(Exception e){ e.printStackTrace(); }
  }

  public String getTime(){
    Calendar c = Calendar.getInstance();
    int date = c.get(Calendar.DATE);
    int month = c.get(Calendar.DAY_OF_MONTH);
    int year = c.get(Calendar.YEAR);
    String time = c.getTime().toString().substring(11,20);
    String currentTime = date + "/" + month + "/" + year + " " + time;

    return currentTime;
  }
}
